<?php
//计算卡结束时间
 function setEndTime($startTime,$buyType=1,$termNum=1) {
        if($buyType==C('VIP_ORDER_BUY_TYPE.YEAR')){
            $end = strtotime($startTime.'+'.$termNum.' year');
        }elseif($buyType==C('VIP_ORDER_BUY_TYPE.MONTH')){
             $end = strtotime($startTime.'+'.$termNum.' month');
        }elseif($buyType==C('VIP_ORDER_BUY_TYPE.WEEK')){
             $end = strtotime($startTime.'+'.$termNum.' week');
        }                      
        return date('Y-m-d', $end);
}
//获取日期型日期
function getCreateDate($time){
    return date('Y-m-d', strtotime($time));
}
//获取预约时刻,如根据t10clock 得到 10
function getBookingTime($clock){
    return substr($clock, 1, -5);
}
function check_wap() {  
    if (isset($_SERVER['HTTP_VIA'])) return true;  
    if (isset($_SERVER['HTTP_X_NOKIA_CONNECTION_MODE'])) return true;  
    if (isset($_SERVER['HTTP_X_UP_CALLING_LINE_ID'])) return true;  
    if (strpos(strtoupper($_SERVER['HTTP_ACCEPT']),"VND.WAP.WML") > 0) {  
        // Check whether the browser/gateway says it accepts WML.  
        $br = "WML";  
    } else {  
        $browser = isset($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : '';  
        if(empty($browser)) return true;
        $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');  
              
        $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');  
              
        $found_mobile=checkSubstrs($mobile_os_list,$browser) ||  
                  checkSubstrs($mobile_token_list,$browser); 
    if($found_mobile)
      $br ="WML";
    else $br = "WWW";
    }  
    if($br == "WML") {  
        return true;  
    } else {  
        return false;  
    }  
}

function checkSubstrs($list,$str){
    $flag = false;
    for($i=0;$i<count($list);$i++){
      if(strpos($str,$list[$i]) > 0){
        $flag = true;
        break;
      }
    }
    return $flag;
}

//a为子集 ，b为整集
function isContainArray($a, $b) {
    
    $c = array_diff($a, $b);
    $flag = empty($c)?1 : 0;
    
    return $flag;
}

function isNullOrEmpty($obj) {
    return (!isset($obj) || empty($obj) || $obj == null);
}

function isHaveSpecialChar($str) {
    $chinese=chr(0xa1)."-".chr(0xff);//中文匹配
    $pattern="/^[a-zA-Z0-9($chinese)]{1,}$/";//加上英文、数字匹配
    
    return !preg_match($pattern,$str); 
}

function hiddenName($name) {
    
    $returnStr = substr($name,0,1) . '***' . substr($name,strlen($name)-1,1);
    
    return $returnStr;
    
}

function calculateDayGap($from, $to) {
   
    $day = ceil(($to-$from)/60/60/24);
    
    return $day;
    
}

function createUuid($prefix = ""){    //可以指定前缀
    $str = md5(uniqid(mt_rand(), true));   
    $uuid  = substr($str,0,8) . '-';   
    $uuid .= substr($str,8,4) . '-';   
    $uuid .= substr($str,12,4) . '-';   
    $uuid .= substr($str,16,4) . '-';   
    $uuid .= substr($str,20,12);   
    return $prefix . $uuid;
}

function getCurrentDate() {
    return date('Y-m-d H:i:s');
}
function toSqlStartTime($time) {
    return $time . ' 00:00:00';
}
function toSqlEndTime($time) {
    return $time . ' 23:59:59';
}
function toSqlIn($str) {
    return '(' . $str . ')';
}
function mms($key,$tel,$content){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send.json");

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
	curl_setopt($ch, CURLOPT_HEADER, FALSE);

	curl_setopt($ch, CURLOPT_HTTPAUTH , CURLAUTH_BASIC);
	curl_setopt($ch, CURLOPT_USERPWD  , 'api:key-'.$key);

	curl_setopt($ch, CURLOPT_POST, TRUE);
	curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile' => $tel,'message' => $content.'【真心代喝】'));

	$res = curl_exec( $ch );
	curl_close( $ch );
	return $res;
}

function getNearestShopIdByLocation($latitude, $longtitude) {
    $shopList = D('shop')->select();
    foreach ($shopList as $key=>$value){
        $id[$key] = $value['shop_id'];
        $distant[$key] = getDistance($latitude, $longtitude, $value['latitude'], $value['longtitude']);
    }

    array_multisort($distant,SORT_NUMERIC,SORT_ASC,$id,SORT_STRING,SORT_ASC,$shopList);
    return $shopList[0];
}

function getPriceByType($shop, $buyType) {
    
    $price = $shop['year_price'];
    
    switch ($buyType) {
        
        case C('VIP_ORDER_BUY_TYPE.YEAR'):
            $price = $shop['year_price'];
            break;
        case C('VIP_ORDER_BUY_TYPE.SEASON'):
            $price = $shop['season_price'];
            break;
        case C('VIP_ORDER_BUY_TYPE.MONTH'):
            $price = $shop['month_price'];
            break;
        default :
            break;
    }
    
    return $price;
    
}

function getEnumString($enum, $value) {
    
    $key = array_search($value, $enum);
    
    $strKey = $key . '_STRING'; 
    
    return $enum[$strKey];
    
}

function rad($d) {
    return $d * 3.1415926535898 / 180.0;
}

function getDistance($lat1, $lng1, $lat2, $lng2) {
    $EARTH_RADIUS = 6378.137;
    $radLat1 = rad($lat1);
    //echo $radLat1;
    $radLat2 = rad($lat2);
    $a = $radLat1 - $radLat2;
    $b = rad($lng1) - rad($lng2);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) +
                            cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s * 10000) / 10000;
    return sprintf("%.2f", $s);
}

function getOneYear($time) {
    return date('Y-m-d H:i:s',strtotime('+1 year',strtotime($time)));
}

function mySort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
    if(is_array($arrays)){
        foreach ($arrays as $array){
            if(is_array($array)){
                $key_arrays[] = $array[$sort_key];
            }else{
                return false;
            }
        }
    }else{
        return false;
    }
    array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
    return $arrays;
}

if (!function_exists('array_column')) {
    function array_column($input, $columnKey, $indexKey = null) {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
        $indexKeyIsNull = (is_null($indexKey)) ? true : false;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
        $result = array();
        foreach ((array) $input as $key => $row) {
            if ($columnKeyIsNumber) {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
            } else {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
            }
            if (!$indexKeyIsNull) {
                if ($indexKeyIsNumber) {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : null;
                    $key = is_null($key) ? 0 : $key;
                } else {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    }
}

function WeSend($openid,$content){
    $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".access_token();
    $post = array(
        "touser" => $openid,
        "msgtype" => "text",
        "text" => array(
            "content" => $content,
        ),
    );
    $data = json_encode2($post);
    $ay = curl($url,$data);
    return $ay;
}

function unserializeToArray($json) {

    if(!isNullOrEmpty($json)) {
        $list = unserialize($json);
    } else {
        $list = array();
    }

    return $list;

}

//获取时差
function timeDiff($begin_time, $end_time )
{
    if ( $begin_time < $end_time ) {
        $starttime = $begin_time;
        $endtime = $end_time;
    } else {
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    $timediff = $endtime - $starttime;
    $days = intval( $timediff / 86400 );
    $remain = $timediff % 86400;
    $hours = intval( $remain / 3600 );
    $remain = $remain % 3600;
    $mins = intval( $remain / 60 );
    $secs = $remain % 60;
    $res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
    return $res;
}